import {ControllerService, TimerControllerService} from "./service";
@Midway.MidwayModule({
    code: "TimerController",
})
class TimerController extends CommonController {
    constructor() {
        super();
        this.metaInfo.name = 'TimerController';
        this.metaInfo.type = ConstVariable.PresenterType.LAUNCHER;

        this.services = {ITimer: [], ITimerOver: []};
        //顺计时或倒计时标志(默认都是顺计时)
        this.sequence = true;
        //总计时
        this.totalSecond = 0;
        //消耗的时间
        this.spendSecond = 0;
        //计时器当前状态; 停止stop,运行running,暂停pause
        this.currentState = "stop";
        //计时器句柄
        this.interval = -1;
        //配置值
        this.modelValue = {};
        //是否启动定时器
        this.isRunTimer = true;
        //是否对时过
        this.isSync = false;
        this.service = undefined;
        //配置控制接口方法
        this.ControlService = new ControllerService(this);
    }

    getService() {
        if(this.service === undefined) {
            this.service = new TimerControllerService(this);
        }
        return this.service;
    }

    $launch() {
        this.isSync = false;
        //设置模型
        this.modelValue.sequence = (this.Model.timer_type !== 'countdown');
        this.modelValue.isPauseOnSubmit = (this.Model.isPauseOnSubmit === true);
        if (this.modelValue.sequence) {
            this.modelValue.totalSecond = 0;
        }
        else {
            this.modelValue.totalSecond = parseInt(this.Model.time_limit);
            (isNaN(this.modelValue.totalSecond)) && (this.modelValue.totalSecond = 0);
        }
        if (this.embedApplication('pptshell') || this.Environment.isWeb) {
            this.addEventListener("PresenterLoaded", ConstVariable.PresenterEventType.IC_PLAYER_EVENT, function () {
                //新特性任务-TQD67291:点击查看学生详情后会加载思维导图组件，加载完成后也会发出该事件，但此时不应该启动计时
                if (!this._hasStartedByPresenterLoaded) {
                    this._hasStartedByPresenterLoaded = true;
                    this._start(false);
                }
            });
        } else {
            this.addEventListener("DefGameQuestion", ConstVariable.PresenterEventType.IC_PLAYER_EVENT, this._taskInfoReceive);
        }
    }

    $release() {
        clearInterval(this.interval);
    }

    _taskInfoReceive(eventData) {
        if (eventData.value && eventData.value.source === 'PresenterLoaded') {
            this._sync(eventData);
            this._start();
        }
    }

    //时间同步
    _sync(servData) {
        var currentTimestamp = this._getCurrentTime();
        if (servData.value && servData.value.source === 'PresenterLoaded') {
            this.isSync = true;

            var startTimestamp = servData.value.startTimestamp,
                submitTimestamp = servData.value.submitTimestamp,
                stopTimestamp = servData.value.stopTimestamp;
            if (stopTimestamp) {
                this.spendSecond = Math.floor((stopTimestamp - startTimestamp) / 1000);
                this.isRunTimer = false;
            } else if (submitTimestamp && submitTimestamp > startTimestamp) {
                var t = (this.modelValue.isPauseOnSubmit) ? submitTimestamp : currentTimestamp;
                this.spendSecond = Math.floor((t - startTimestamp) / 1000);
                //this.isRunTimer = false;
            } else if (currentTimestamp > startTimestamp) {
                this.spendSecond = Math.floor((currentTimestamp - startTimestamp) / 1000);
            }

            if (this.modelValue.sequence) {
                this.modelValue.totalSecond += this.spendSecond;
            } else {
                this.modelValue.totalSecond -= this.spendSecond;
            }
        }
    }

    _step() {
        var self = this;
        this.spendSecond++;
        if (this.currentState != 'pause') {
            $.each(self.services.ITimer, function (k, v) {
                v.setTimeValue(self.totalSecond);
            });
        }
    }

    //开始计时
    _start(isUseModel, startTime) {
        if (this.currentState == 'stop') {
            if (isUseModel === false) {
                this.totalSecond = 0;
                this.sequence = true;
            } else {
                this.totalSecond = this.modelValue.totalSecond;
                this.sequence = this.modelValue.sequence;
            }
            if (this.isSync !== true) {
                if (startTime) {
                    this.spendSecond = Math.floor((this._getCurrentTime() - startTime) / 1000);
                    if (this.sequence) {
                        this.totalSecond += this.spendSecond;
                    } else {
                        this.totalSecond -= this.spendSecond;
                    }
                } else {
                    this.spendSecond = 0;
                }
            }
            else if (startTime != undefined && startTime != null) {
                this.isRunTimer = true; //支持思维导图多次交互特性，状态恢复bug-99606、99658 修复
                this.spendSecond = Math.floor((this._getCurrentTime() - startTime) / 1000);
                if (this.sequence) {
                    this.totalSecond = this.spendSecond;
                } else {
                    this.totalSecond -= this.spendSecond;
                }
            }
            var self = this;
            //为组件设置默认值
            $.each(self.services.ITimer, function (k, v) {
                v.initTimeValue(self.totalSecond);
            });
            //开始计时
            if (this.isRunTimer) {
                this.interval = setInterval(function () {
                    if (self.sequence) {
                        //顺计时
                        self.totalSecond++;
                        self._step();
                    } else {
                        if (self.totalSecond > 0) {
                            self.totalSecond--;
                            self._step();
                        }
                        if (self.totalSecond <= 0) {
                            $.each(self.services.ITimerOver, function (k, v) {
                                v.onTimeOver(self.spendSecond);
                            });
                            self._stop();
                            self.totalSecond = 0;
                        }
                    }
                }, 1000);
            }
        }
        if (this.isRunTimer) {
            this.currentState = 'running';
        }
    }

    _pause(isStopTime) {
        //当前计时器在运行或暂停状态
        if (this.currentState == 'running') {
            this.currentState = 'pause';
            (isStopTime !== false) && this._stop();
        }
    }

    //停止计时
    _stop() {
        if (this.currentState == 'running' || this.currentState == 'pause') {
            clearInterval(this.interval);
            this.currentState = 'stop';
        }
    }

    _getCurrentTime() {
        var locTime;
        if (window.ClassroomUtils && (typeof ClassroomUtils != 'undefined') && ClassroomUtils.getMasterSystemTimeMS) {
            locTime = ClassroomUtils.getMasterSystemTimeMS();
            //getMasterSystemTimeMS
            locTime = locTime == 0 ? new Date().getTime() : locTime;
        } else {
            locTime = new Date().valueOf();
        }
        return locTime;
    }
}